#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    socket = new QTcpSocket();
    //连接信号槽
    connect(socket,&QTcpSocket::readyRead,this,&MainWindow::socket_Read_Data);
    connect(socket,&QTcpSocket::disconnected,this,&MainWindow::socket_Disconnected);

    ui->pushButton_Send->setEnabled(false);

}

MainWindow::~MainWindow()
{
    delete this->socket;
    delete ui;
}

void MainWindow::on_pushButton_Connect_clicked()
{
    if (ui->pushButton_Connect->text() == tr("连接")){
        QString IP;
        int port;
        //获取IP地址
        IP = ui->lineEdit_IP->text();
        qDebug() << IP;
        //获取端口号
        port = ui->lineEdit_Port->text().toInt();

        qDebug() << port;
        //取消已有的连接
        socket->abort();
        //连接服务器
        socket->connectToHost(IP,port);

        //等待连接成功
        if (!socket->waitForConnected(30000)){
            qDebug() << "Connection failed";
            return;
        }
        qDebug() << "connect successfully";

        //发送按键使能
        ui->pushButton_Connect->setEnabled(true);
        ui->pushButton_Connect->setText("断开连接");
    } else {
        //断开连接
        socket->disconnectFromHost();
        ui->pushButton_Connect->setText("连接");
        ui->pushButton_Connect->setEnabled(false);
    }
}

void MainWindow::on_pushButton_Send_clicked()
{
    qDebug() << "Send :" << ui->textEdit_Send->toPlainText();
    socket->write(ui->textEdit_Send->toPlainText().toLatin1());
    socket->flush();
}

void MainWindow::socket_Read_Data()
{
    QByteArray buffer;
    buffer = socket->readAll();
    if (!buffer.isEmpty()){
        ui->textEdit_Recv->setText("");
        ui->textEdit_Recv->setText(tr(buffer));
    }
}

void MainWindow::socket_Disconnected()
{
    ui->pushButton_Send->setEnabled(false);
    ui->pushButton_Connect->setText("连接");
    qDebug() << "Disconnect";
}


